package com.lanchetech.user.controller;


import com.baidu.fsg.uid.UidGenerator;
import com.lanchetech.bean.request.LoginReq;
import com.lanchetech.bean.request.RegisterReq;
import com.lanchetech.bean.request.SmsCodeReq;
import com.lanchetech.bean.request.UpdatePasswordByPhoneReq;
import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.common.enums.DeletedEnum;
import com.lanchetech.common.enums.MsgUserRoleEnum;
import com.lanchetech.common.enums.MsgUserStatusEnum;
import com.lanchetech.dao.MsgUserMapper;
import com.lanchetech.dao.UserMapper;
import com.lanchetech.entity.MsgUser;
import com.lanchetech.entity.User;
import com.lanchetech.service.SmsService;
import com.lanchetech.user.config.JwtAuthenticationRequest;
import com.lanchetech.user.service.AuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Api(value = "登录注册管理接口", tags = "登录注册管理接口")
@RequestMapping("/api/auth")
@RestController
public class AuthController {

    @Value("${jwt.header}")
    String tokenHeader;

    @Autowired
    AuthService authService;

    @Autowired
    SmsService smsService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    MsgUserMapper msgUserMapper;

    @Resource
    UidGenerator uidGenerator;

    @ApiOperation("用户短信验证码登录")
    @PostMapping("/login")
    public ResultData<String> createAuthenticationToken(
            @RequestBody LoginReq req) throws AuthenticationException {
        return authService.login(req);
    }

    @ApiOperation("用户密码登录")
    @PostMapping("/loginByPassword")
    public ResultData<String> loginByPassword(
            @RequestBody LoginReq req) throws AuthenticationException {
        return authService.loginByPassword(req);
    }

    @ApiOperation("用户通过openid自动登录")
    @GetMapping("/loginByOpenid")
    public ResultData<String> createAuthenticationToken(@RequestParam("code") String code) {
        return authService.loginByOpenid(code);
    }

    @ApiOperation("用户刷新登录token")
    @GetMapping("/refresh")
    public ResultData<String> refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws AuthenticationException {
        String token = request.getHeader(tokenHeader);
        return authService.refresh(token);
    }

    @ApiOperation("小程序手机号用户注册")
    @PostMapping("/register")
    public ResultData<String> register(@RequestBody RegisterReq req) throws AuthenticationException {
        return authService.register(req);
    }

    @ApiOperation("小程序授权用户注册")
    @PostMapping("/wxRegister")
    public ResultData<String> wxRegister(@RequestBody RegisterReq req) throws AuthenticationException {
        return authService.wxRegister(req);
    }

    @ApiOperation("APP用户注册")
    @PostMapping("/appRegister")
    public ResultData<String> appRegister(@RequestBody RegisterReq req) throws AuthenticationException {
        return authService.appRegister(req);
    }

    @ApiOperation("获取验证码图片")
    @GetMapping("/captcha")
    public ResultData<String> getKaptchaImage(HttpServletResponse response, HttpSession session) throws Exception {
        return authService.getKaptchaImage(response, session);
    }

    @ApiOperation(value = "发送短信验证码")
    @PostMapping("/sendSmsCode")
    public BaseResp sendSms(HttpServletRequest request, HttpSession session, @RequestBody SmsCodeReq req) {
        return smsService.sendSms(request, session, req);
    }

    @ApiOperation(value = "用户忘记密码，手机验证并修改用户密码")
    @PostMapping("/updatePasswordByPhone")
    public BaseResp updatePasswordByPhone(@RequestBody UpdatePasswordByPhoneReq req) {
        return authService.updatePasswordByPhone(req);
    }

    @ApiOperation(value = "获取指定手机号的注册状态和角色")
    @GetMapping("/getPhoneStatus")
    public ResultData<String> getPhoneStatus(@RequestParam("phone") String phone) {
        return authService.getPhoneStatus(phone);
    }

    @ApiOperation(value = "发送登录或注册的短信验证码")
    @PostMapping("/sendVerificationSmsCode")
    public BaseResp sendVerificationSmsCode(HttpServletRequest request, @RequestBody SmsCodeReq req) {
        return smsService.sendVerificationSmsCode(request, req);
    }

    @ApiOperation(value = "修改用户安全密码")
    @GetMapping("/updatePayPassword")
    public BaseResp updatePayPassword(@RequestParam("payPassword") String payPassword, @RequestParam("code") String code) {
        return authService.updatePayPassword(payPassword, code);
    }

    @ApiOperation(value = "使用用户安全密码伪登录")
    @GetMapping("/loginByPayPassword")
    public BaseResp loginByPayPassword(@RequestParam("payPassword") String payPassword, @RequestParam("type") Byte type) {
        return authService.loginByPayPassword(payPassword, type);
    }

    @ApiOperation(value = "判断用户是否已经进行过伪登录")
    @GetMapping("/isPayLogin")
    public ResultData<Boolean> isPayLogin(@AuthenticationPrincipal User user, @RequestParam("type") Byte type) {
        return authService.isPayLogin(user, type);
    }

    @ApiOperation(value = "测试")
    @GetMapping("/testPWLjaV9SxYdWq7r3mS")
    public BaseResp test() {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        List<User> userList = userMapper.findAll();
        userList.stream().forEach(user -> {
            MsgUser result = msgUserMapper.findOneByRelateIdAndRole(user.getId(), MsgUserRoleEnum.USER.getRole());
            if (result == null) {
                msgUserMapper.insert(MsgUser.builder()
                        .username(Long.toString(uidGenerator.getUID()))
                        .password(encoder.encode(Long.toString(uidGenerator.getUID())))
                        .lastPasswordResetDate(new Date())
                        .status(MsgUserStatusEnum.IN_SERVICE.getStatus())
                        .relateId(user.getId())
                        .nickname(user.getNickname())
                        .avatar(user.getAvatar())
                        .role(MsgUserRoleEnum.USER.getRole())
                        .tenantId(null)
                        .createdAt(new Date())
                        .updatedAt(new Date())
                        .deleted(DeletedEnum.DEFAULT.getStatus())
                        .build());
            }
        });
        return new BaseResp();
    }
}
